with Ada.Text_IO;
with Ada.Strings.Unbounded;
with Ada.Strings.Unbounded.Text_IO;

package body Properties is

   package SU renames Ada.Strings.Unbounded;

   function Get_Properties (File : String) return Pairs_Type is

      use SU;

      Inputfile                  : Ada.Text_IO.File_Type;
      Buffer, Key, Value         : SU.Unbounded_String;
      N                          : Natural := 1;
      Lines                      : Natural := 0;
      KV                         : Boolean := False;

   begin
      Ada.Text_IO.Open (Inputfile, Ada.Text_IO.In_File, File);
      while not Ada.Text_IO.End_Of_File (Inputfile) loop
         SU.Text_IO.Get_Line(Inputfile,Buffer);
         if not (SU.Element (Buffer, 1) = '#') then
            Lines := Lines + 1;
         end if;
      end loop;
      Ada.Text_IO.Close (Inputfile);
      declare
         Properties              : Pairs_Type (1 .. Lines);
      begin
         Ada.Text_IO.Open (Inputfile, Ada.Text_IO.In_File, File);
         while not Ada.Text_IO.End_Of_File (Inputfile) loop
            KV := False;
            Text_IO.Get_Line(Inputfile, Buffer);
            if not (Element (Buffer, 1) = '#') then
               for I in 1 .. Length (Buffer) loop
                  if Element (Buffer, I) = '=' then
                     KV := True;
                  else
                     if KV then
                        Append (Value, Element (Buffer, I));
                     else
                        Append (Key, Element (Buffer, I));
                     end if;
                  end if;
               end loop;
               if (Key = Null_Unbounded_String) or
                 (Value = Null_Unbounded_String) then
                  raise Properties_Exception;
               end if;
               while Element (Key, 1) = ' ' loop
                  Delete (Key, 1, 1);
               end loop;
               while Element (Key, Length (Key)) = ' ' loop
                  Delete (Key, Length (Key), Length (Key));
               end loop;
               while Element (Value, 1) = ' ' loop
                  Delete (Value, 1, 1);
               end loop;
               while Element (Value, Length (Value)) = ' ' loop
                  Delete (Value, Length (Value), Length (Value));
               end loop;
               Pair.Set_Key (Properties (N), To_String (Key));
               Pair.Set_Value (Properties (N), To_String (Value));
               Key := Null_Unbounded_String;
               Value := Null_Unbounded_String;
               N := N + 1;
            end if;
         end loop;
         return Properties;
      end;
   end Get_Properties;
end Properties;
